from flask import Flask, request, jsonify, render_template
import json
import os
from datetime import datetime

app = Flask(__name__)

# 确保subjects文件夹存在
SUBJECTS_DIR = 'subjects'
if not os.path.exists(SUBJECTS_DIR):
    os.makedirs(SUBJECTS_DIR)

# 初始化科目文件
SUBJECTS = ['语文', '数学', '英语', '生物', '地理', '政治', '历史', '物理']
for subject in SUBJECTS:
    filename = f'{SUBJECTS_DIR}/{subject}.json'
    if not os.path.exists(filename):
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/resources/<subject>')
def get_resources(subject):
    try:
        with open(f'{SUBJECTS_DIR}/{subject}.json', 'r', encoding='utf-8') as f:
            data = json.load(f)
        return jsonify(data)
    except Exception as e:
        print(f"Error in get_resources: {str(e)}")  # 添加日志
        return jsonify({'error': str(e)}), 500

@app.route('/api/upload', methods=['POST'])
def upload_resource():
    try:
        data = request.get_json()  # 使用get_json()而不是request.json
        if not data:
            return jsonify({'error': 'No data provided'}), 400

        subject = data.get('subject')
        if not subject or subject not in SUBJECTS:
            return jsonify({'error': 'Invalid subject'}), 400

        # 验证必需字段
        required_fields = ['filename', 'downloadLink']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'error': f'Missing {field}'}), 400

        # 读取现有数据
        filename = f'{SUBJECTS_DIR}/{subject}.json'
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                resources = json.load(f)
        except FileNotFoundError:
            resources = []
        except json.JSONDecodeError:
            resources = []

        # 添加新资源
        new_resource = {
            'filename': data['filename'],
            'date': data.get('date', datetime.now().strftime('%Y-%m-%d')),
            'downloadLink': data['downloadLink'],
            'preview': data.get('preview', '')
        }
        
        resources.append(new_resource)

        # 保存更新后的数据
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(resources, f, ensure_ascii=False, indent=2)

        return jsonify({'message': 'Resource added successfully', 'resource': new_resource})
    except Exception as e:
        print(f"Error in upload_resource: {str(e)}")  # 添加日志
        return jsonify({'error': str(e)}), 500

@app.route('/api/search/<subject>')
def search_resources(subject):
    query = request.args.get('query', '').lower()
    try:
        with open(f'{SUBJECTS_DIR}/{subject}.json', 'r', encoding='utf-8') as f:
            resources = json.load(f)
        
        if query:
            filtered_resources = [
                r for r in resources 
                if query in r['filename'].lower()
            ]
            return jsonify(filtered_resources)
        return jsonify(resources)
    except Exception as e:
        print(f"Error in search_resources: {str(e)}")  # 添加日志
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)
